package controller;

import cn.hutool.core.io.file.FileNameUtil;
import cn.hutool.core.util.IdUtil;
import org.springframework.web.bind.annotation.PostMapping;
import org.springframework.web.bind.annotation.RequestParam;
import org.springframework.web.bind.annotation.RestController;
import org.springframework.web.multipart.commons.CommonsMultipartFile;
import vo.AjaxResult;

import javax.servlet.http.HttpServletRequest;
import java.io.File;
import java.io.IOException;

/**
 * Author：汤小洋
 * Date：2023-12-18 14:13
 * Description：<描述>
 */
@RestController
public class FileController {

    @PostMapping("/upload")
    public AjaxResult upload(String name, @RequestParam CommonsMultipartFile avatar, HttpServletRequest req) throws IOException {
        System.out.println(name);
        System.out.println(avatar.getOriginalFilename()); // 文件名
        System.out.println(avatar.getSize()); // 文件大小
        System.out.println(avatar.getInputStream()); // 文件流

        String uploadPath = req.getServletContext().getRealPath("upload");// 上传的文件夹的绝对路径
        String filename = IdUtil.simpleUUID() + "." + FileNameUtil.getSuffix(avatar.getOriginalFilename()); // 生成文件名
        String filePath = uploadPath + "/" + filename; // 上传文件的绝对路径
        System.out.println(filePath);

        avatar.transferTo(new File(filePath)); // 保存文件

        return AjaxResult.success();
    }

}
